var purchasingAll = (function ($, W, D) {
    return {
        //supplier:1,动态赋值，用于判断是否已加载了供货商数据
        init: function () {
            purchasingAll.loadWarehouse();
            // purchasingAll.loadAlibabaAccount();
            purchasingAll.reloadPage({
                pageNo: 1,
                pageSize: 100
            });
        },
        // 加载仓库
        loadWarehouse: function (fn) {
            $.ajax({
                type: 'post',
                url: 'dxmPurchasePlan/loadSupplierAndWarehouse.json',
                dataType: 'json',
                success: function (data) {
                    var warehouseList = data.warehouseList,
                        $allWarehouse = $("#allWareHosePurchasingId");
                    if (!warehouseList.length) {
                        var str = '<div class="prompt-con-in inline-block p-right10">暂无仓库，子账号可联系主账号增加权限</div>';
                        $allWarehouse.removeClass('pTop10').addClass('m-top5').append(str);
                    } else {
                        var first = '<a href="javascript:" class="mRight20 myj-aFocus myj-active"  id="-1" onclick="purchasingAll.changeWareHouse(this)">全部</a>';
                        $allWarehouse.append($(first));
                        $.each(warehouseList, function (index, val) {
                            var a1 = '<a href="javascript:void(0)" class="mRight20 myj-aFocus"  id="' + val.id + '" onclick="purchasingAll.changeWareHouse(this)">' + val.name + '</a>';
                            $allWarehouse.append($(a1));
                        });
                    }

                    // var html = "<option value=''>全部</option>";
                    // for(var i = 0; i < warehouseList.length; i++){
                    //     html += "<option value="+warehouseList[i].id+">"+warehouseList[i].name+"</option>"
                    // }
                    // $allWarehouse.html(html);
                    if (typeof fn === "function") {
                        fn();//记载数据后如果要执行某动作
                    }
                }
            });

        },
        // 切换仓库
        changeWareHouse: function (obj) {
            var type = $(obj).attr('id');
            if (type == -1) {
                $("#searchWarehoseId").val('');
            } else {
                $("#searchWarehoseId").val(type);
            }
            purchasingAll.setClass(obj);
            purchasingAll.reloadPage();
        },
        //加载1688店铺
        loadAlibabaAccount: function (fn) {
            $.ajax({
                type: 'post',
                url: 'dxmPurchasingNote/getAliBabaAuth.json',
                data: {},
                dataType: 'json',
                success: function (data) {
                    if (data) {
                        var authAliBabaList = data.authAliBabaList,
                            $alibabaAccount = $("#alibabaAccountSel");

                        $alibabaAccount.empty();
                        var html = "<option value=''>全部</option>";
                        for (var i = 0; i < authAliBabaList.length; i++) {
                            html += "<option value=" + authAliBabaList[i].id + ">" + authAliBabaList[i].name + "</option>"
                        }
                        $alibabaAccount.html(html);
                        if (typeof fn === "function") {
                            fn();//记载数据后如果要执行某动作
                        }
                    }
                }
            });
        },
        showSearchType: function (that) {
            var type = $(that).data('val'),
                $searchType = $('.searchType').find('a[data-val=' + type + ']'),
                $ul = $(that).parent();
            if ($searchType.length <= 0) {
                $.fn.message({type: 'error', msg: '搜索类型不存在！'});
                return;
            }
            if ($searchType.hasClass('myj-hide')) {
                $searchType.addClass('myj-aFocus');
                $searchType.removeClass('myj-hide');
            }
            $(that).addClass('myj-hide');
            if ($ul.find('li.myj-hide').length >= $ul.find('li').length) {
                $ul.parent().css('display', 'none');
            }
            purchasingAll.setSearchType($searchType.get(0));
        },
        setSearchType: function (that) {
            $("#searchType").val($(that).data('val'));
            purchasingAll.setClass(that);
            purchasingAll.setSearchValuePlaceholder();
            MULTI_SEARCH.closeText(); //关闭已打开的多个搜索 textarea
        },
        setSearchValuePlaceholder: function () {
            var searchType = $('.searchType').find('.myj-active').data('val'),
                searchMode = $('.searchMode').val(),
                $searchValue = $('#searchValue');
            //还要考虑模糊匹配，暂未
            switch (searchType + '') {
                case '0' :
                    $searchValue.attr('placeholder', '多个采购单号用逗号隔开，最多支持200个');
                    break;
                case '2' :
                    $searchValue.attr('placeholder', '多个商品SKU用逗号隔开，最多支持200个');
                    break;
                case '1' :
                    $searchValue.attr('placeholder', '');
                    break;
                case '4' :
                    $searchValue.attr('placeholder', '多个1688单号用逗号隔开，最多支持200个');
                    break;
                case '5' :
                    $searchValue.attr('placeholder', '');
                    break;
                case '3' :
                    $searchValue.attr('placeholder', '多个运单号用逗号隔开，最多支持200个');
                    break;
                case '6' :
                    $searchValue.attr('placeholder', '多个商品编码用逗号隔开，最多支持200个');
                    break;
                case '7' :
                    $searchValue.attr('placeholder', '多个关联单号间用逗号隔开，最多支持200个');
                    break;
                case '8' :
                    $searchValue.attr('placeholder', '');
                    break;
                default:
            }
        },
        setCurState: function (that) {
            // purchasingAll.setCheckBoxState(that);
            purchasingAll.setClass(that);
            purchasingAll.reloadPage();
        },
        setSubmitState: function (that) {
            // purchasingAll.setCheckBoxState(that);
            purchasingAll.setClass(that);
            purchasingAll.reloadPage();
        },
        //设置按钮选中状态
        setButtonItemStyle: function (that) {
            // 手工采购没有 1688 退款状态筛选
            if ($(that).attr('data-val') === '3') {
                purchasingAll.setClass($('a[name="refundStatus"]:first-child'));
                $('.refundStatusBox').addClass('hide');
            } else {
                $('.refundStatusBox').removeClass('hide');
            }
            purchasingAll.setClass(that);
            purchasingAll.reloadPage();
        },
        setMsgMark: function (that) {
            purchasingAll.setCheckBoxState(that);
            purchasingAll.reloadPage();
        },
        setSurplusPredict: function (that) {
            purchasingAll.setClass(that);
            purchasingAll.reloadPage();
        },
        setPurchasingPx: function (that) {
            purchasingAll.setOrderClass(that);
            purchasingAll.reloadPage();
        },
        //设置多选框状态
        setCheckBoxState: function (obj) {
            if ($(obj).hasClass('allSelect')) {
                $(obj).removeClass('myj-active');
                $(obj).addClass('myj-active');
                $(obj).siblings().find('input[type="checkbox"]:checked').prop('checked', false);
            } else {
                $(obj).parent().siblings('.allSelect').removeClass('myj-active');
                //如果全部都未选择
                if ($(obj).parent().parent().find('input[type="checkbox"]:checked').length == 0) {
                    $(obj).parent().siblings('.allSelect').addClass('myj-active');
                }
            }
        },
        //设置多选框状态，高级搜索
        setCheckBoxState2: function (obj) {
            var $td = $(obj).closest('td'),
                type = $(obj).is(':checked'),
                $ipt = $td.find('input[type="checkbox"]:not(.allSelect)'),
                $iptCheck = $td.find('input[type="checkbox"]:not(.allSelect):checked');

            if($(obj).hasClass('allSelect')) {
                $td.find('input[type="checkbox"]:not(.allSelect)').prop('checked', type);
            }else{
                if(!type){
                    $td.find('.allSelect').prop('checked', false);
                }else{
                    $td.find('.allSelect').prop('checked', $ipt.length === $iptCheck.length);
                }
            }
        },
        //切换的选中状态-- % >
        setClass: function (obj) {
            $(obj).parent().find(".myj-active").removeClass("myj-active");
            $(obj).addClass("myj-active");
        },
        setOrderClass: function (obj) {
            var isDesc;
            if ($(obj).find('.myjCaretDown').length > 0) {
                isDesc = 'Y';
            }
            $(obj).parent().find('.myj-active').removeClass('myj-active');
            $(obj).parent().find('.myjCaretUp').removeClass('myjCaretUp');
            $(obj).parent().find('.myjCaretDown').removeClass('myjCaretDown');
            $(obj).addClass('myj-active');
            if (isDesc) {
                $(obj).find('span').addClass('myjCaretUp');
            } else {
                $(obj).find('span').addClass('myjCaretDown');
            }
        },
        advancedSearch: function () {
           //采购数量
            var quantityLeft = $.trim($('#purchaseQuantityLeft').val()),
                quantityRight = $.trim($('#purchaseQuantityRight').val()),
                $errorPurchaseMsg = $('.errorPurchaseMsg');

            $errorPurchaseMsg.empty();
            if (quantityLeft && quantityRight) {
                if (+quantityLeft > +quantityRight) {
                    $('.errorPurchaseMsg').text('开始数量不能大于结束数量');
                    return;
                }
            }
            purchasingAll.reloadPage();
        },
        showAndHideAdvancedSearch: function () {
            var $advancedSearchDiv = $('#productListAdvancedSearch'),
                value = $advancedSearchDiv.attr('data-value');
            //清空错误信息
            $('.errorPurchaseMsg').empty();
            if (+value) {
                $advancedSearchDiv.hide();
                $advancedSearchDiv.attr('data-value', 0);
                $('#isAdvancedSearch').val('');
                $('.advanceSearchHide').css('display', 'block');
                // $('#searchValue').prop('disabled', false);
                // $('#btnSearch').prop('disabled', false);
                // $('#searchMode').prop('disabled', false);
                purchasingAll.resetVal();
            } else {
                $advancedSearchDiv.show();
                $advancedSearchDiv.attr('data-value', 1);
                $('#isAdvancedSearch').val('Y');
                $('.advanceSearchHide').css('display', 'none');
                // $('#searchValue').prop('disabled', true);
                // $('#btnSearch').prop('disabled', true);
                // $('#searchMode').prop('disabled', true)
                //填充供货商
                purchasingAll.fillSupplier('allPurchaseSupplierSel');
                //填充采购员
                purchasingAll.fillAccessUser('allPurchaseBuyerSel');
                //填充1688账号
                purchasingAll.fillAlibabaAccount('allPurchaseAccountSel');
            }
        },
        resetVal: function () {
            var form = $('form.doNotSubmit').get(0);
            $('.chosen-select').val('');
            form.reset();
            $('.errorPurchaseMsg').empty();
        },

        //批量保存预计到货时间按或运单号
        savePredictTimeOrYdh: function () {
            var predictTypeOrYdh = $('#predictTimeOrYdh').val();
            var obj = '';
            var box = [];
            if (predictTypeOrYdh == '1') {
                return purchasingTracking.saveTrackingCodeNum();
            } else {
                $('#loading').modal('show');
                obj = $('#batchOperateCgdContent').find('tr td input[type="text"]');
                obj.each(function () {
                    box.push({"purchasingNoteId": $(this).attr("purchasingNoteId"), "timeOrYdh": $(this).val()});
                });
            }

            $.ajax({
                type: 'post',
                url: 'dxmPurchasingNote/savePurchasingNotePredictTimeOrYdh.json',
                data: {
                    "boxStr": JSON.stringify(box),
                    "predictTimeOrYdh": predictTypeOrYdh
                },
                dataType: 'json',
                success: function (data) {
                    if (data > 0) {
                        $('#loading').modal('hide');
                        $.fn.message({type: "success", msg: "操作成功!"});
                    }
                    reloadPro();
                },
                error: function () {
                    $('#loading').modal('hide');
                    $.fn.message({type: "error", msg: "操作失败!"});
                    reloadPro();
                }
            });
        },
        reloadPage: function (options) {
            var data = purchasingAll.getQueryData(options);

            var searchType = data.searchType;
            if(!searchType){
                $.fn.message({type:"error", msg:"选择搜索类型!"});
                return;
            }
            var $searchValue = $('#searchValue'),
                searchValue = data.searchValue;
            if (searchType == '0' || searchType == '2' || searchType == '3' || searchType == '4' || searchType == '6') {
                MULTI_SEARCH.closeText(); //关闭已打开的多个搜索 textarea
                if (searchValue) {
                    var val = searchValue.replace(/，/g,','),
                        skuCode = val.split(',');
                    if(skuCode.length > 200){
                        var newContent = skuCode.slice(0, 200),
                            newStr = newContent.join(',');
                        $searchValue.val(newStr);
                        data.searchValue = newStr;
                    }
                }
            }

            $('#loading').modal('show');
			
			//测试数据
			var html = purchasingAllPageListData()
			var commentColors = $('#commentColors').val();
			if (commentColors) {
			    commentColors = commentColors.split(',');
			    $.each(commentColors, function (i, j) {
			        $('div[uid="commentColor"] span[data-val="' + j + '"]').addClass('bgCommentFocus').html('<span class="glyphicon glyphicon-ok"></span>');
			    });
			}
			$('#pageList').html(html);
			$('#loading').modal('hide');
			return ;
            $.post(gitWinLocHref() + 'dxmPurchasingNote/purchasingAllPageList.htm', data, function (html) {
                var commentColors = $('#commentColors').val();
                if (commentColors) {
                    commentColors = commentColors.split(',');
                    $.each(commentColors, function (i, j) {
                        $('div[uid="commentColor"] span[data-val="' + j + '"]').addClass('bgCommentFocus').html('<span class="glyphicon glyphicon-ok"></span>');
                    });
                }
                $('#pageList').html(html);
            }).always(function () {
                $('#loading').modal('hide');
            });
        },
        /**
         * 获取查询参数
         */
        getQueryData: function (options) {
            var $purchasingPxDivId = $('#purchasingPxDivId'),
                authorizationId = $('#alibabaAccountSel').val(),
                data = {
                    pageNo: options && options.pageNo ? options.pageNo : 1,
                    pageSize: options && options.pageSize ? options.pageSize : $('#pageSize').val(),
                    searchType: $('#searchType').val(),
                    searchValue: $.trim($('#searchValue').val()),
                    searchMode: $('#searchMode').val(), // 0模糊匹配 1精确匹配 2完全匹配
                    commentColors: $('#commentColors').val(), //获取采购备注颜色
                    warehoseId: $('#searchWarehoseId').val(), // 仓库id
                    authorizationId: authorizationId || '', // 加载1688店铺
                    purchasingPx: $purchasingPxDivId.find('.myj-active').data('val'), // 排序方式 4:按采购单号 1:按创建时间 2:按更新时间 5:按供货商名
                    purchasingPxVal: $purchasingPxDivId.find('.myjCaretDown').length ? 'desc' : 'asc',

                },
                isAdvanceSearch = $('#isAdvancedSearch').val() === 'Y' ? 'Y' : ''; //是否是高级搜索
            data.searchValue = MYJ.escapeChar(data.searchValue, function(match, str){
                if (match === '\\' && data.searchMode !== '2') return '\\' + str;
            });

            //是否是高级搜索
            if (isAdvanceSearch === 'Y') {
                data.isAdvanceSearch = isAdvanceSearch;
                if (data.searchValue.length > 2048) {
//                        高级搜索内容不能超过2048个字符
                    $.fn.message({type: 'error', msg: '搜索内容不能超过2048字符'});
                    return;
                }
                //时间
                var minPrice = $('#purchasingMinPrice').val(),//采购金额
                    tempMinPrice = +minPrice,
                    maxPrice = $('#purchasingMaxPrice').val(),//采购金额
                    tempMaxPrice = +maxPrice,
                    createTimeLeft = $('#createTimeLeft').val(),//创建时间
                    createTimeRight = $('#createTimeRight').val(),
                    checkTimeLeft = $('#checkTimeLeft').val(),//审核时间
                    checkTimeRight = $('#checkTimeRight').val(),
                    predictTimeLeft = $('#predictTimeLeft').val(),//到货时间
                    predictTimeRight = $('#predictTimeRight').val(),
                    endTimeLeft = $('#endTimeLeft').val(),//到货时间
                    endTimeRight = $('#endTimeRight').val(),
                    suppliderId = $('#allPurchaseSupplierSel').val(),//供货商id
                    agentId = $('#allPurchaseBuyerSel').val(),//采购员
                    alibabaAccount = $('#allPurchaseAccountSel').val() ,//1688账号
                    quantityLeft = $.trim($('#purchaseQuantityLeft').val()),
                    quantityRight = $.trim($('#purchaseQuantityRight').val());

                if (!(tempMinPrice !== tempMinPrice) && tempMinPrice > 0) {
                    // 填写的是数字并且大于0
                    data.priceLeft = tempMinPrice;
                }
                //采购数量
                if (quantityLeft) {
                    data.quantityLeft = quantityLeft;
                }

                if (quantityRight) {
                    data.quantityRight = quantityRight;
                }

                if (!(tempMaxPrice !== tempMaxPrice) && tempMaxPrice > 0 && tempMaxPrice > tempMinPrice) {
                    data.priceRight = tempMaxPrice;
                }

                if (createTimeLeft) {
                    data.createStartTime = createTimeLeft;
                }
                if (createTimeRight) {
                    data.createEndTime = createTimeRight;
                }
                if (endTimeLeft) {
                    data.endTimeStart = endTimeLeft;
                }
                if (endTimeRight) {
                    data.endTimeEnd = endTimeRight;
                }
                /* if (checkTimeLeft) {
                      data.checkStartTime =checkTimeLeft;
                  }
                  if (checkTimeRight) {
                      data.checkEndTime = checkTimeRight;
                  }*/

                if (predictTimeLeft) {
                    data.arriveStartTime = predictTimeLeft;
                }
                if (predictTimeRight) {
                    data.arriveEndTime = predictTimeRight;
                }
                //供货商
                if (suppliderId) {
                    data.supplierId = suppliderId;
                }
                if (data.supplierId) {
                    //指定了供货商，若搜索类型为供货商，则不予处理
                    if ('1' == data.searchType) {
                        data.searchValue = '';
                    }
                }
                //采购员
                if (agentId) {
                    data.agentId = agentId;
                }

                //1688账号
                if (alibabaAccount) {
                    data.authorizationId = alibabaAccount;
                }

                //结算方式
                var settleType = $('#allPurchaseSettleTypeSel').val();
                if (settleType) {
                    data.settlementMethod = settleType;
                }

                var isAlibaba = $('input[name=advanceIsAlibaba]:checked').val();
                if (isAlibaba) {
                    data.isAlibaba = isAlibaba;
                }
                var isHaveIdentifyNo = $('input[name=advanceIsHaveIdentifyNo]:checked').val();
                if (isHaveIdentifyNo) {
                    data.isHaveIdentifyNo = isHaveIdentifyNo;
                }
                //下单状态
                var $curStates = $('input[type=checkbox][name=advanceCurState]:checked'),
                    temp;
                if ($curStates.length) {
                    temp = [];
                    $curStates.each(function (i, th) {
                        if ($(th).val()) {
                            temp.push($(th).val());
                        }
                    });
                    if (temp.length)
                        data.curStates = temp.join(',');
                }
                /*  $curStates = $('input[type=checkbox][name=advanceCurState][value!=""]:checked'); //获取下单状态选择集合，不包括全部
                  if ($curStates.length === 1) {
                      data.onlyChooseOneCS = 'Y';
                  }*/
                //付款状态
                $submitStates = $('input[type=checkbox][name=advanceSubmitState]:checked');
                if ($submitStates.length) {
                    temp = [];
                    $submitStates.each(function (i, th) {
                        if ($(th).val()) {
                            temp.push($(th).val());
                        }
                    });
                    if (temp.length)
                        data.submitStates = temp.join(',');
                }
                // $submitStates = $('input[type=checkbox][name=advanceSubmitState][value!=""]:checked');
                if ($('#advanceMsgMark').prop('checked')) {
                    data.hasComment = 'Y';
                    data.hasRemark = 'Y';
                    data.noHasComment = 'Y';
                } else {
                    if ($('#advanceHasComment:checked').length > 0) data.hasComment = 'Y';
                    if ($('#advanceHasRemark:checked').length > 0) data.hasRemark = 'Y';
                    if ($('#advanceNoHasComment:checked').length > 0) data.noHasComment = 'Y';
                }

                /*  var spt = $('input[name=advanceSurplusPredict]:checked').val();
                  if (spt) {
                      data.surplusPredictType = spt;
                  }*/
            } else {
                // data.searchType = $('.searchType').find('.myj-active').data('val');

                // data.searchValue = $.trim($('#searchValue').val());

                //状态筛选
                $curStates = $('a[name="curState"].myj-active').data('val');
                if ($curStates) {
                    data.curStates = $curStates;
                    data.onlyChooseOneCS = 'Y';
                }

                //付款状态
                var $submitStates = $('a[name="submitState"].myj-active').data('val');
                if ($submitStates) {
                    data.submitStates = $submitStates;
                }
                // 退款状态
                data.refundStatus = $('a[name="refundStatus"].myj-active').data('val');
                //采购类型
                var purchaseType = $('a[name="purchaseType"].myj-active').data('val');
                if (typeof purchaseType === 'number') {
                    data.isAlibaba = purchaseType;
                }
                //物流信息
                var waybill = $('a[name="waybill"].myj-active').data('val');
                if (typeof waybill === 'number') {
                    data.isHaveIdentifyNo = waybill;
                }
                /* if ($('#msgMark').hasClass('.myj-active')) {
                     data.hasComment = 'Y';
                     data.hasRemark = 'Y';
                 } else {
                     if ($('#hasComment:checked').length > 0) {}data.hasComment = 'Y';
                     if ($('#hasRemark:checked').length > 0) {}data.hasRemark = 'Y';
                 }*/

                //剩余到货的类型，不同类型有不同处理方式
                data.surplusPredictType = $('.surplusPredictType').find('.myj-active').data('val');
            }
            return data;
        },
        /** 搜索中选中备注颜色 **/
        setSearchCommentColor: function (obj) {
            if ($(obj).is('.bgCommentFocus')) {
                $(obj).removeClass('bgCommentFocus').html('');
            } else {
                $(obj).addClass('bgCommentFocus').html('<span class="glyphicon glyphicon-ok"></span>');
            }
            //获取选中的备注颜色数据
            var foo = $('div[uid="commentColor"] span'),
                commentColors = '';
            $(foo).each(function () {
                if ($(this).is('.bgCommentFocus')) {
                    commentColors += $(this).attr('data-val') + ',';
                }
            });
            commentColors = commentColors.substr(0, commentColors.length - 1);
            $('#commentColors').val(commentColors);
        },
        // 审核弹框层
        verifyOrderDialog: function (that, orderNumber) {
            var id = $(that).closest('tr').attr('id');
            $("#tishiId").val(id);
            $("#tishiHeader").text("审核");
            $("#tishiHiddenHeader").val(orderNumber);
            var nrxsTwo = '<b>确定审核通过吗？</b>';
            $("#tishiBodyFirst").html(nrxsTwo);
            $("#tishiBodyTwo").find('.tishiBodyTwoTitle').html('采购单为：');
            $("#tishiBodyTwo").find('.tishiBodyTwoCon').html(orderNumber);
            $("#warningModel").modal('show');
            $('#canChangeButton').attr('onclick', 'purchasingComm.truePayMoneyPurchasing()');

        },
        // 编辑采购单之前增加验证逻辑
        editBefore: function (obj, pageType) {
            // 验证采购单存在与否
            var zt = $('#zt').val(),
                id = zt == 'wait_pay' ? $(obj).closest('tr').attr('id') : $(obj).closest('tr').attr('purchasingId');

            $.ajax({
                url: requestUrl + 'dxmPurchasingNote/checkPurchasing.json',
                data: {id: id},
                async: false,
                success: function (data) {
                    if (data.code == 1) {
                        $('span[uid="checkMsg"]').text(data.msg);
                        $('button.checkPurchasing').attr('data-Id', id + '');
                        $('#checkPurchasing').modal('show');
                        return;
                    }
                    comOpenWinPost(requestUrl + 'dxmPurchasingNote/edit.htm?pageType=' + pageType + '&id=' + id);
                }
            })
        },
        cancelRevoke: function (id) {
            if (!id) {
                $.fn.message({type: "error", msg: '请选择还原的采购单！'});
                return;
            }
            myjAlert.confirm({
                'content': "<p><b>确定还原此采购单吗？</b></p>",
                'callback': function (v) {
                    if (v) {
                        var url = "dxmPurchasingNote/cancelRevoke.json";
                        $('#loading').modal('show');
                        $.get(
                            url,
                            {
                                id: id
                            },
                            function (data) {
                                $('#loading').modal('hide');
                                if (data.code > 0) {
                                    // 重新加载一下页面
                                    $.fn.message({type: "success", msg: '还原采购单成功！'});
                                    initCgdTj();//采购单统计
                                    purchasingAll.loadOrderCountOfArrivalTime();//剩余到货
                                    purchasingAll.reloadPage();
                                } else {
                                    $.fn.message({type: "error", msg: data.message});
                                }
                            }
                        );
                    }
                }
            })

        },
        /**
         * 删除已取消采购单
         * @param purchasingNoteId 采购单id
         * @param type 采购单类型 1-手动采购单 2-1688采购单
         */
        deletePurchasingNote: function (purchasingNoteId) {
            if (!purchasingNoteId) {
                $.fn.message({type: "error", msg: "请选择需要删除的采购单"});
                return;
            }
            myjAlert.confirm({
                'content': "<p><b>确定删除此采购单吗？</b></p>",
                'callback': function (v) {
                    if (v) {
                        url = "dxmPurchasingNote/deletePurchasingNote.json";
                        $('#loading').modal('show');
                        $.get(
                            url,
                            {
                                id: purchasingNoteId
                            },
                            function (data) {
                                $('#loading').modal('hide');
                                if (+data.code == 0) {
                                    // 重新加载一下页面
                                    $.fn.message({type: "success", msg: '删除采购单成功！'});
                                    initCgdTj();
                                    purchasingAll.loadOrderCountOfArrivalTime();//剩余到货
                                    purchasingAll.reloadPage();
                                    // reloadPage("dxmPurchasingNote/waitPayPageList.htm?state=" + $('#zt').val() + "&searchWarehoseId=" + $("#searchWarehoseId").val());
                                } else {
                                    $.fn.message({type: "error", msg: data.msg});
                                }
                            }
                        );
                    }
                }
            })
        },
        //删除
        delPurchasing: function (that, purNoAll) {
            var id = $(that).closest('tr').attr('id');
            myjAlert.confirm({
                'content': "<p><b>您确认删除采购单吗？</b></p><p>采购单号：" + purNoAll + "</p>",
                'callback': function (v) {
                    if (v) {
                        var url = "dxmPurchasingNote/deletePurchasingNote.json";
                        $('#loading').modal('show');
                        $.get(
                            url,
                            {
                                id: id
                            },
                            function (data) {
                                $('#loading').modal('hide');
                                if (+data.code == 0) {
                                    $.fn.message({type: 'success', msg: '您的' + purNoAll + '采购单删除成功!'});
                                    // 重新加载一下页面
                                    reloadPro();
                                } else {
                                    $.fn.message({type: 'error', msg: '您的' + purNoAll + '采购单删除失败！'});
                                }
                            }
                        );
                    }
                }
            })
        },
        //取消采购单
        payedCancelDialog: function (that, po) {
            var $tr = $(that).closest('tr'),
                isAlibaba = $tr.attr('data-isAlibaba'),
                id = $tr.attr('id');
            $('#isCancelAlibaba').prop('checked', false);
            $('.cancelAlibabaBox')[+isAlibaba ? 'removeClass' : 'addClass']('hide');
            $('#payedCancelPoId').text(po);
            $('#payedCancelCommentId').val("");
            $('#payedCancelId').modal('show');
            $('#payedCancelzjId').val(id);
        },
        //终止剩余到货
        partGoodsEndDialog: function (that, po) {
            var id = $(that).closest('tr').attr('id');
            $('#partGoodsEndPoId').text(po);
            $('#partGoodsEndCommentId').val("");
            $('#partGoodsEndId').modal('show');
            $('#partGoodsEndzjId').val(id);
        },
        //填充供货商
        fillSupplier: function (supplierDomId) {
            //判断是否已获取或供货商数据
            if (!purchasingAll['supplier']) {
                $.get("dxmSupplier/getSupplierForPurchasing.json", {},
                    function (data) {
                        if (data) {
                            var optionX = '<option value="">--请选择供货商--</option>',
                                $select = $("#" + supplierDomId);
                            $.each(data, function (index, val) {
                                optionX += "<option value='" + index + "'>" + val + "</option>";
                            });
                            $select.html(optionX);
                            $select.chosen("destroy").chosen({
                                search_contains: true//注册插件
                            });
                            // $select.val(-1);
                            $('.chosen-container').css('width', '200px');
                            purchasingAll['supplier'] = 1;
                        }
                    },
                    'json'
                );
            }
        },
        //填充采购员
        fillAccessUser: function (accessDomId) {
            if (purchasingAll['accessUser']) {
                return;
            }
            $.post('dxmPurchasingNote/getAccessUser.json', {}, function (data) {
                var idObj = $('#' + accessDomId);
                if (data) {
                    var $agentOption = '<option value="">--请选择采购员--</option>';
                    $.each(data, function (i, j) {
                        $agentOption += "<option value='" + i + "'>" + j + "</option>";
                    });
                    idObj.html($agentOption);
                    // idObj.val(0);
                    idObj.chosen("destroy").chosen({
                        search_contains: true//注册插件
                    });
                    purchasingAll['accessUser'] = 1;
                    $('.chosen-container').css('width', '200px');
                }
            });
        },
        //填充1688账号
        fillAlibabaAccount: function (alibabaDomId) {
            if (purchasingAll['alibabaAccount']) {
                return;
            }
            $.ajax({
                type: 'post',
                url: 'alibabaOrder/getAlibabaAccount.json',
                async: false,
                success: function (data) {
                    if (data) {
                        var html = '<option value="">选择1688下单账号</option>';
                        for (var i = 0; i < data.length; i++) {
                            html += '<option value=' + data[i].id + '>' + data[i].name + '</option>';
                        }
                        var $accountObj = $('#' + alibabaDomId);
                        $accountObj.html(html);
                        $accountObj.chosen("destroy").chosen({
                            search_contains: true//注册插件
                        });
                        purchasingAll['alibabaAccount'] = 1;
                        $('.chosen-container').css('width', '200px');
                    }
                }
            });
        },
        // 全部采购订单的导出不走该方法，搬至jsp文件中
        showExportExcel: function (type) {
            var paramData = {};
            if (type == '2') {
                //按勾选
                //仓库
                var warehouseId = $('#searchWarehoseId').val();
                paramData.warehouseId = warehouseId;
                paramData.exportFlag = type;
                paramData.actionType = type;
            } else if (type == '3') {
                //按所有页
                var url = "dxmPurchasingNote/batchPurchasingExcelAllBySelNew.json";
                paramData = purchasingAll.getQueryData();
                //更换名称
                if (paramData.warehoseId) {
                    paramData.searchWarehoseId = paramData.warehoseId;//仓库
                }

                if (paramData.isHaveIdentifyNo) {
                    //是否添加了运单号
                    paramData.isIndentifyNoExist = paramData.isHaveIdentifyNo;
                    delete paramData.isHaveIdentifyNo;
                }
                if (paramData.isAlibaba) {
                    paramData.is1688Note = paramData.isAlibaba;//是否1688采购单
                }
            }
            purchasingComm.showExportExcel(type, paramData);
        },
        //获取各天数对应的剩余到货采购单数量
        loadOrderCountOfArrivalTime:function () {
            $.get("dxmPurchasingNote/purchasingAllOrderCountOfArrivalTime.json",{},function (data) {
                if (data){
                    //各天数
                    $("span.arrivalTimeType_d1").text(data['arrivalTimeType_d1']);
                    $("span.arrivalTimeType_d2").text(data['arrivalTimeType_d2']);
                    $("span.arrivalTimeType_d3").text(data['arrivalTimeType_d3']);
                    $("span.arrivalTimeType_d7").text(data['arrivalTimeType_d7']);
                    $("span.arrivalTimeType_d7More").text(data['arrivalTimeType_d7More']);
                    $("span.arrivalTimeType_overdue").text(data['arrivalTimeType_overdue']);
                }
            })
        }
    }
})(jQuery, window, document);